from common.config import new_config
from common.enum import MyEnum
import argparse
import sys


class InvalidM(Exception):
    pass


def display_option(option):
    i = 1
    for o in option:
        print(i, o.desc)
        i += 1


def call_runner(runner):
    f = runner.func
    f()


def get_command(all_runner):
    while True:
        i = input("\nenter action of number you want to perform>>")
        if i.lower() in ["q", "quit"]:
            sys.exit(0)
        elif i.lower() in ["d", "display"]:
            display_option(all_runner)
        else:
            call_runner(all_runner[int(i)-1])


def get_act(env, conf, m):
    if conf.is_win():
        from win.do import WinAct
        return WinAct(env, conf)
    else:
        from suse.do import SUSEAct
        from ubuntu.do import UbuntuAct
        if m not in ["server", "laptop"]:
            raise InvalidM("invalid mode '%s'" % m)
        if conf.is_opensuse():
            return SUSEAct(env, conf, m)
        if conf.is_ubuntu():
            return UbuntuAct(env, conf, m)


if __name__ == '__main__':
    # TODO select privilege
    config = new_config()
    print("env is %s" % config.env)
    parser = argparse.ArgumentParser()
    parser.add_argument('-auto', action="store_true", default=False, help="auto restore")
    parser.add_argument('-m', help="run mode, server or laptop")
    args, _ = parser.parse_known_args()
    try:
        act = get_act(config.env, config, args.m)
    except InvalidM as e:
        print(e)
        parser.print_help()
        sys.exit(1)
    runner_map = act.all_runner()
    if args.auto:
        # auto perform
        for r in runner_map[MyEnum.restore_auto.value]:
            print(r.desc)
            call_runner(r)
    else:
        print("\n", "#"*50, sep="")
        print("a. using -auto switch to active auto mode  \n")
        print("b. input q or quit to exit\n")
        print("c. input d or display to print all action\n")
        print("", "#"*50, sep="")
        display_option(runner_map[MyEnum.restore_all.value])
        get_command(runner_map[MyEnum.restore_all.value])
